package com.xyf.basicrtc

import android.media.MediaCodec
import android.media.MediaFormat.*
import android.util.Log
import android.view.Surface

class DecodeH264 constructor(surface: Surface, width:Int, height:Int) {
    lateinit var mediaCodec: MediaCodec

    init {
        try {
            mediaCodec = MediaCodec.createDecoderByType(MIMETYPE_VIDEO_AVC)
            val mediaFormat = createVideoFormat(MIMETYPE_VIDEO_AVC, width, height)
            mediaFormat.setInteger(KEY_BIT_RATE, width * height)
            mediaFormat.setInteger(KEY_FRAME_RATE, 15)
            mediaFormat.setInteger(KEY_I_FRAME_INTERVAL, 5)
            mediaCodec.configure(mediaFormat, surface, null, 0)
            mediaCodec.start()
        } catch (exc: Exception) {
            Log.e(TAG, "初始化MediaCodec失败", exc)
        }
    }

    fun decode(data: ByteArray) {
        Log.i(TAG, "接收到消息: " + data.size)
        val index = mediaCodec.dequeueInputBuffer(100000)
        if (index >= 0) {
            val inputBuffer = mediaCodec.getInputBuffer(index)
            inputBuffer?.clear()
            inputBuffer?.put(data, 0, data.size)
            mediaCodec.queueInputBuffer(index, 0, data.size, System.currentTimeMillis(), 0)

            val bufferInfo = MediaCodec.BufferInfo()
            var outBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 100000)
            while (outBufferIndex >= 0) {
                mediaCodec.releaseOutputBuffer(index,true)
                outBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0)
            }
        }
    }

    companion object {
        const val TAG = "MediaDecode"
    }

}